//var abc = {};
$(function(){
initializeMap();
        var eventName = jQuery(':input[id=eventName]');
        var eventDescription = jQuery(':input[id=eventDescription]');
        var eventWebsite = jQuery(':input[id=eventWebsite]');
        var eventAddress = jQuery(':input[id=eventAddress]');
        var eventType = jQuery(':input[id=eventType]');
        var manualEventCategory = jQuery(':input[id=manualEventCategory]');
        jQuery(':input[id=setServiceTimesDiv]')
        var imageUploadButton = $(".imageUpload");
        imageUploadButton.click(function(){
      //window.open('http://www.weatherreports.com/');
      var load = window.open('http://localhost/newGoogleRep/eventsmanager/upload_image.php','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
  })
//if($("#setServiceTimesDiv").length <= 0)
//    {
//        jQuery("#setServiceTimesDiv").html("Time Spans are not currently set.")
//    }
       var allFields = jQuery([]).add(eventName).add(eventDescription).add(eventAddress).add(eventType).add(manualEventCategory).add(eventWebsite);
        

$('.registerEvent').button();
$('.timeSpanSelector').button();
$('#selectOtherButton').button();
$('#eventLocationSelector').button();
$("#addOtherCategoriesDiv").hide();

$( ".imageUpload" ).button({
            icons: {
                primary: "ui-icon-image",
                secondary: "ui-icon-image"
            },
                        text: true
        });

$('#selectOtherButton').click(function(){
 if (jQuery("#selectOtherButton:checked").val() == "on" )
    {
$("#addOtherCategoriesDiv").slideDown('slow');
    }
    else
        {
$("#addOtherCategoriesDiv").slideUp('slow');
manualEventCategory.val('');
        }
});

$('#submitEvent').click(function(){

 var bValid = true;
 allFields.removeClass('ui-state-error');
    $("#serviceTimesDiv").removeClass('ui-state-error');
     $("#eventLocationDiv").removeClass('ui-state-error');
bValid = bValid && formValidator.checkLength(eventName,"event name field",4,55);
bValid = bValid && formValidator.checkRegexp(eventName,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The event name field only allows alphanumeric characters (a-z 0-9).");
bValid = bValid && formValidator.checkLength(eventDescription,"event description field",10,150);

if (eventWebsite.val().length > 0)
    {
          bValid = bValid && formValidator.checkRegexp(eventWebsite,/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,"Enter a valid url, eg. http://www.wits.ac.za");
    }
 bValid = bValid && formValidator.checkLength(eventAddress,"event address field",10,150);
 if (!$("#eventType option:selected").length)
{

}
if (jQuery("#selectOtherButton:checked").val() == "on" )
    {
      bValid = bValid && formValidator.checkLength(manualEventCategory,"manual event type field",3,105);
      bValid = bValid && formValidator.checkRegexp(manualEventCategory,/^[a-zA-Z 0-9\,]*$/ ,"Only a comma sperated list with alphanumeric characters are allowed (a-z 0-9).");
    }
if (activeTimesArray.length <1)
        {
        bValid = false;
         $("#serviceTimesDiv").addClass('ui-state-error');
         formValidator.updateErrorMessage("Please insert at least one activity that is conducted inside your facility.");
        }
        if (eventCoorindateArray.length < 1)
            {
        bValid = false;
         $("#eventLocationDiv").addClass('ui-state-error');
         formValidator.updateErrorMessage("A location is not selected. Please select a geo-coordinates for your facility.");
            }


    if (bValid) {
   sendRequest.setAction('addNewEvent');

//var userType1 = $("input:radio[name=userType]:checked").val();
var eventTypeDropDown = $("#eventType").val();

var eventTypeMaualInput = manualEventCategory.val();
eventType = eventTypeDropDown+" "+eventTypeMaualInput;

var activeTimesData = JSON.stringify(activeTimesArray);
var eventCoorindateData = JSON.stringify(eventCoorindateArray);
//$(".errorMessageDiv").html("lhfsdf"+a);
formData = {'eventName':eventName.val(),'eventDescription':eventDescription.val(),'eventWebsite':eventWebsite.val(),'eventAddress':eventAddress.val(),'eventType':eventType,'serviceTimes': activeTimesData,"eventCoordinates":eventCoorindateData};
sendRequest.setSendParameters(formData);
$(".errorMessageDiv").load(sendRequest.serverURL, sendRequest.getSendData(), function(){
//hiddenResponseDiv.unbind();
if ($(".errorMessageDiv").html() == "1")
    {
       $(".errorMessageDiv").html('');
        jQuery("#dialog-eventRegOKMessage").dialog('open');
    }
});
    }

});

$("#dialogue-confirm").dialog({
            resizable: true,
            width: 740,
            modal: true,
            show: 'clip',
            hide: 'clip',
                        autoOpen: false,
            closeOnEscape: true
});

$("#dialog-event-location-map").dialog({
            //resizable: true,
            width: 740,
            height: 740,
            modal: true,
            show: 'clip',
            hide: 'clip',
                        autoOpen: true,
            closeOnEscape: true,
            buttons: {
              'Insert': function() {

var successful = true;
if (markersArray.length <1)
    {
        successful = false;
        formValidator.updateErrorMessage("A location is not selected. Please select a geo-coordinates for your facility.");
    }
    if (successful)
        {
           eventCoorindateArray[0] = eventCoordinates;
           $("#setEventLocation").html( eventCoordinates.listEventCoordinates());
                                   $(".deleteEventLocation").button({

                        icons: {
                            primary: 'ui-icon-scissors'
                        },
                        text: false
                    });
                     jQuery(this).dialog("close");


              $(".deleteEventLocation").click(function(){
var elementToBeDeleted = $(this).parent();
           // $(this).unbind();

                jQuery( "#dialogue-confirm").dialog({ title: 'Confirm Delete Event Location' });
            jQuery( "#dialogue-confirm").html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This event geolocation will be deleted and cannot be recovered. Are you sure?</p>');
            jQuery( "#dialogue-confirm").dialog("open");
            jQuery(  "#dialogue-confirm" ).dialog( "option", "buttons", {
                "Delete Location": function() {
eventCoordinates.emptyObject();
                   eventCoorindateArray.length = 0;
    jQuery(this).dialog("close");
    elementToBeDeleted.remove();
     deleteOverlays();
                },  "Cancel": function() {
                    jQuery(this).dialog("close");
                }
            });

          });


        }

              } ,"Cancel": function() {
                    jQuery(this).dialog("close");
                }
            }
            });


var eventNameForTimeSpan = jQuery(':input[id=eventNameForTimeSpan]');
var activityDescription = jQuery(':input[id=activityDescription]');
var activityRequirements = jQuery(':input[id=activityRequirement]');
  $("#dialogue-time-selector").dialog({
            resizable: true,
            width: 740,
            modal: true,
            show: 'clip',
            hide: 'clip',
                        autoOpen: false,
            closeOnEscape: true,
            buttons: {
              'Insert': function() {
 slideTime();

  var bValid = true;
 eventNameForTimeSpan.removeClass('ui-state-error');
activityDescription.removeClass('ui-state-error');
activityRequirements.removeClass('ui-state-error');
 bValid = bValid && formValidator.checkLength(eventNameForTimeSpan,"activity name field",4,55);
bValid = bValid && formValidator.checkRegexp(eventNameForTimeSpan,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The activity name field only allows alphanumeric characters (a-z 0-9).");
bValid = bValid && formValidator.checkLength(activityDescription,"activity description field",4,55);
bValid = bValid && formValidator.checkRegexp(activityDescription,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The activity description field only allows alphanumeric characters (a-z 0-9).");
bValid = bValid && formValidator.checkLength(activityRequirements,"activity requirements field",4,55);
bValid = bValid && formValidator.checkRegexp(activityRequirements,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The activity requirements field only allows alphanumeric characters (a-z 0-9).");
var liveAtiveTimesObject = new activeTimesObject(currentActiveTimesParametersStorer.startHour,currentActiveTimesParametersStorer.startMin,currentActiveTimesParametersStorer.endHour,currentActiveTimesParametersStorer.endMin,eventNameForTimeSpan.val(),activityDescription.val(),activityRequirements.val());

test =true;
            for ( i=0; i < activeTimesArray.length; i++ )
        {

           bValid = bValid && activeTimesArray[i].checkTimeConflict(liveAtiveTimesObject.startHour,liveAtiveTimesObject.startMin,liveAtiveTimesObject.endHour,liveAtiveTimesObject.endMin);
if (bValid == false)
    {
       formValidator.updateErrorMessage("Current set time span conflicts with the previous set of inserted time spans.");
       break;
    }
          
        }
        
if (bValid)
    {
    activeTimesArray[activeTimesArray.length] =   liveAtiveTimesObject;
    $("#setServiceTimesDiv").append(liveAtiveTimesObject.listSetTime(parseInt(activeTimesArray.length-1)));
                       $(".deleteTimeSpanButton").button({

                        icons: {
                            primary: 'ui-icon-scissors'
                        },
                        text: false
                    });
//if (activeTimesArray.length-1 == 0)
//    {
var index = parseInt(activeTimesArray.length-1);
             $("#time_span_button_"+index).click(function(){
var elementToBeDeleted = $(this).parent();
           // $(this).unbind();

            currentIndex = parseInt($(this).attr('title'));
 
                jQuery( "#dialogue-confirm").dialog({ title: 'Confirm Delete Activity' });
            jQuery( "#dialogue-confirm").html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This time span with its associated activity will be deleted and cannot be recovered. Are you sure?</p>');
            jQuery( "#dialogue-confirm").dialog("open");
            jQuery(  "#dialogue-confirm" ).dialog( "option", "buttons", {
                "Delete Activity": function() {
                   activeTimesArray[currentIndex]=null;
        var newArr = new Array();
        for (k in activeTimesArray) if(activeTimesArray[k]) newArr.push(activeTimesArray[k])
    activeTimesArray=  newArr;
    jQuery(this).dialog("close");
    elementToBeDeleted.remove();
                },  "Cancel": function() {
                    jQuery(this).dialog("close");
                }
            });
            
          });
//    }



    jQuery(this).dialog('close');



    }


                    }
                ,
                'Cancel': function() {
                             jQuery(this).dialog('close');

                }
            }
            });
     //   });

$(".timeSpanSelector").click(function(){

 $("#dialogue-time-selector").dialog('open');
});
$("#eventLocationSelector").click(function(){
 
//               $("#dialog-event-location-map").dialog( "option", "buttons", {
//                "Set Event Location": function() {
//
//    jQuery(this).dialog("close");
//
//                },  "Cancel": function() {
//                    jQuery(this).dialog("close");
//                }
//            });
// initializeMap(25,25);
  //$("#map_canvas").clone().prependTo("#mapping");

            $("#dialog-event-location-map").dialog('open');
//             sendRequest.setAction('getBusinessEventMap');
//               sendRequest.setSendParameters(null);
//               $('#googleMapContent').load(sendRequest.serverURL, sendRequest.getSendData(), function(){
//
//               });
});


           jQuery("#dialog-eventRegOKMessage").dialog({
            resizable: true,
            width:450,
            autoOpen: false,
            modal: true,
            hide: 'puff',
            show: 'puff',
            buttons: {
                'OK': function() {
                    jQuery(this).dialog('close');
                     allFields.removeClass('ui-state-error');
    $("#serviceTimesDiv").removeClass('ui-state-error');
     $("#eventLocationDiv").removeClass('ui-state-error');
      allFields.val('');
     activeTimesArray.length = 0;
       eventCoorindateArray.length = 0;
 $("#setServiceTimesDiv").empty();
  $("#setEventLocation").empty();
            }
        }
        });
 $("#dialog-event-location-map").dialog('close');

});

